var pomelo = require('pomelo');
var utils = require('../../util/utils');
var PlayerState = require('../../domain/common/playerState');
var STATE = PlayerState.STATE;
var playerStateDao = module.exports;

playerStateDao.getPlayerState = function (name, cb) {
    var sql = 'select * from player_state where name = ?';
    var args = [name];
    pomelo.app.get('dbclient').query(sql, args, function (err, res) {
        if (res.length > 0) {
            var row = res[0];
            var playerState = new PlayerState({
                id: row.id, name: row.name, state: row.state, extra: row.extra
            });
            utils.invokeCallback(cb, null, playerState);
        } else {
            utils.invokeCallback(cb, null, {});
        }
    });
};

playerStateDao.updatePlayerState = function (name, state, extra, cb) {
    var sql = 'update player_state set state = ?, extra = ? where name = ?';
    var args = [state, extra, name];
    pomelo.app.get('dbclient').query(sql, args, function (err, res) {
        if (!!err) {
            utils.invokeCallback(cb, {code: err.number, msg: err.message}, null);
        } else {
            utils.invokeCallback(cb, null, res);
        }
    });
};

playerStateDao.createPlayerState = function (name, extra, cb) {
    var sql = 'insert into player_state (name, state, extra) values (?, ?, ?) on duplicate key update state = ?';
    var state = STATE.AFTER_LOGIN;
    var args = [name, state, extra, state];
    pomelo.app.get('dbclient').insert(sql, args, function (err, res) {
        if (!!err) {
            console.error('create player state failed! ' + err.stack);
            utils.invokeCallback(cb, {code: err.number, msg: err.message}, null);
        } else {
            var playerState = new PlayerState({id: res.insertId, name: name, state: state});
            utils.invokeCallback(cb, null, playerState);
        }
    });
};

